package org.linlinjava.litemall.wx.util;

import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;


import java.util.Map;

public class MerchantPermissionDialect extends MybatisPermissionDialect {
    private final Log log = LogFactory.getLog(MerchantPermissionDialect.class);

    // 全表加过滤
    @Override
    public String permissionSql(MappedStatement ms, String sql) {
        StringBuilder sbSql = new StringBuilder(sql);

        Subject subject = SecurityUtils.getSubject();
        String merchantId = "0"; // 客户端没有商户ID就不给取数
        //如果有动态参数 merchantId
        String mchtid =(String) subject.getSession().getAttribute("X-Litemall-mchtid");
        //log.info("X-Litemall-mchtid");
        //log.info(mchtid);
        if( StringUtils.isNotBlank(mchtid)){
            merchantId = mchtid;
        }

        /*
        if(StringUtils.isNotBlank(merchantId)){
            sbSql = new StringBuilder("select * from (")
                    .append(sbSql)
                    .append(" ) s ")
                    .append(" where s.merchant_id = "+ merchantId +" ");
        }
        */

        // log.info("WXAPI权限拼装SQL：" + sbSql.toString());

        return sbSql.toString();
    }


    @Override
    public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
        return null;
    }
}
